package com.project.common.tools;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.project.common.config.WeiXinH5Config;
import com.project.common.constant.RedisConstant;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Component
public class WeixinH5Utils {
    @Resource
    private WeiXinH5Config weiXinH5Config;
    @Resource
    private RedisTemplate redisTemplate;

    public static String createSignature(String token, String timestamp, String nonce, String[] params) {
        // 将参数按ASCII码从小到大排序（字典序）
        if(params!=null){
            Arrays.sort(params);
        }
        // 拼接字符串
        StringBuilder sb = new StringBuilder();
        sb.append("token=").append(token).append("&")
                .append("timestamp=").append(timestamp).append("&")
                .append("nonce=").append(nonce).append("&");
        if(params!=null){
            for (String param : params) {
                sb.append(param).append("&");
            }
        }
        sb.deleteCharAt(sb.length() - 1);  // 删除最后一个"&"
        // 加密签名
        String signature = sha1(sb.toString());
        return signature;
    }

    private static String sha1(String input) {
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-1");
            byte[] digest = md.digest(input.getBytes());
            return bytesToHex(digest);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("Could not find SHA-1 algorithm.", e);
        }
    }

    private static String bytesToHex(byte[] bytes) {
        StringBuilder hex = new StringBuilder();
        for (byte b : bytes) {
            hex.append(String.format("%02x", b));
        }
        return hex.toString();
    }

   /* public static void main(String[] args) {
        String token = "your_token";
        String timestamp = "1503616000";
        String nonce = "12345678";
        String[] params = {"param1", "param2", "param3"};

        String signature = createSignature(token, timestamp, nonce, params);
        System.out.println("Signature: " + signature);
    }*/

    public String getAccessToken(){
        try {
            String accessToken = (String) redisTemplate.opsForValue().get(RedisConstant.WeiXin.H5_TOKEN);
            if(StrUtil.isBlank(accessToken)){
                String res = HttpUtil.get("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+weiXinH5Config.getAppId()+"&secret="+weiXinH5Config.getSecret());
                if(StrUtil.isNotBlank(res)){
                    JSONObject jsonObject = JSONUtil.parseObj(res);
                    if(jsonObject.get("access_token")!=null){
                        accessToken = jsonObject.get("access_token").toString();
                        redisTemplate.opsForValue().set(RedisConstant.WeiXin.H5_TOKEN,accessToken,7100, TimeUnit.SECONDS);
                    }
                }
            }
            return accessToken;
            /*String tokenObj = HttpClientUtils.doGet1("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+access_token+"&type=jsapi",null);
            JSONObject jsonObjects = JSONObject.parseObject(tokenObj);
            ticket = jsonObjects.get("ticket").toString();
            System.out.println(access_token);*/
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    public JSONObject getShare(){
        String timeLong = System.currentTimeMillis()+"";
        String nonceStr = UUID.randomUUID().toString().replaceAll("-","");
        String accessToken = getAccessToken();
        String sing = createSignature(accessToken,timeLong,nonceStr,null);
        JSONObject shareInfo = new JSONObject();
        shareInfo.putOnce("appId",weiXinH5Config.getAppId());
        shareInfo.putOnce("timestamp",timeLong);
        shareInfo.putOnce("nonceStr",nonceStr);
        shareInfo.putOnce("signature",sing);
        return shareInfo;
    }

}